package com.pan.tools;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ConvertObject {

    public static <T> T convertObject(T newObject,Object oldObject){
        Class oldClass = oldObject.getClass();
        Field[] oldFields = oldClass.getDeclaredFields();
        Field[] newFields = newObject.getClass().getDeclaredFields();

        Map<String,Class> oldMap = Arrays.stream(oldFields)
                .collect(Collectors.toMap(Field::getName,Field::getType));
        Arrays.stream(newFields).forEach(field -> {
            String memberName = field.getName();
            Class memberType = field.getType();
            if (oldMap.get(memberName) == memberType){
                try {
                    Field oldField = oldClass.getDeclaredField(memberName);
                    oldField.setAccessible(true);
                    Object value = oldField.get(oldObject);
                    field.setAccessible(true);
                    field.set(newObject,value);
                } catch (NoSuchFieldException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return newObject;
    }

    public static <T> T copySameParameter(T vObj, Object cObj){
        Field[] vFields = vObj.getClass().getDeclaredFields();
        Field[] cFields = cObj.getClass().getDeclaredFields();
        HashMap<String,Object> cMap = Arrays.stream(cFields).collect(HashMap::new,(m,f)->{
            try {
                f.setAccessible(true);
                m.put(f.getName(),f.get(cObj));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        },HashMap::putAll);
        Arrays.stream(vFields).forEach(field -> {
            Object cValue = cMap.get(field.getName());
            if (cValue!=null){
                field.setAccessible(true);
                try {
                    field.set(vObj,cValue);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return vObj;
    }


}
